
package ma.crawler;

import ma.util.FileUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

// 文件格式
//{
//    regex:"([12])12345",
//    group:[
//      {
//          name:"所有配置",
//          index:0
//      },
//      {
//          name:"xxx",
//          index:1
//      }
//    ]
//}

public class RegexConfig {

    public static class Group {

        public String mName;
        public int mIndex;

        public String mValue;

        public Group(String name, int index) {
            mName = name;
            mIndex = index;
        }

        public void setValue(String value) {
            mValue = value;
        }

        public String getValue() {
            return mValue;
        }
    }

    public static RegexConfig initConfig(String path) {
        String text = FileUtil.readFile(new File(path));
        RegexConfig config = new RegexConfig();
        try {
            JSONObject jsonObject = new JSONObject(text);
            config.mRegex = jsonObject.optString("regex");
            JSONArray group = jsonObject.optJSONArray("group");

            int length = group.length();
            List<Group> list = new ArrayList<Group>(length);
            for (int i = 0; i < length; i++) {
                JSONObject groupObject = group.optJSONObject(i);
                String name = groupObject.optString("name");
                int index = groupObject.optInt("index");
                list.add(new Group(name, index));
            }
            config.mGroupList = list;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return config;
    }

    public String mRegex;
    public List<Group> mGroupList;

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (Group g : mGroupList) {
            builder.append(g.mName).append(":").append(g.mValue).append("\t");
        }
        builder.append("\n");
        return builder.toString();
    }

    public void printTitleToFile(File file) {
        StringBuilder builder = new StringBuilder();
        for (Group g : mGroupList) {
            builder.append(g.mName).append("\t");
        }
        builder.append("\n");
        String text = builder.toString();
        FileUtil.saveToFile(file, text, true, "utf-8");
    }

    public void printValueToFile(File file) {
        StringBuilder builder = new StringBuilder();
        for (Group g : mGroupList) {
            builder.append(g.mValue).append("\t");
        }
        builder.append("\n");
        String text = builder.toString();
        FileUtil.saveToFile(file, text, true, "utf-8");
    }
}
